package com.atguigu.flink;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.ExecutionEnvironment;
import org.apache.flink.api.java.operators.AggregateOperator;
import org.apache.flink.api.java.operators.DataSource;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.util.Collector;


/**
 * 做一个flink小案例(有界数据批处理)
 */
public class demo01 {
    public static void main(String[] args) throws Exception {
        //创建环境变量
        ExecutionEnvironment executionEnvironment = ExecutionEnvironment.getExecutionEnvironment();

        //通过执行环境读取文件
        DataSource<String> stringDataSource = executionEnvironment.readTextFile("input/word.txt");

        AggregateOperator<Tuple2<String, Long>> result = stringDataSource.flatMap(new FlatMapFunction<String, String>() {
            @Override
            public void flatMap(String s, Collector<String> collector) throws Exception {
                String[] s1 = s.split(" ");
                for (String str : s1) {
                    collector.collect(str);
                }
            }
        }).map(new MapFunction<String, Tuple2<String, Long>>() {
            @Override
            public Tuple2<String, Long> map(String value) throws Exception {
                //参考scala写法
                return Tuple2.of(value, 1L);
            }
        })
                //这里的groupby是根据传入的参数位置进行聚合
                .groupBy(0).sum(1);

        //最终结果打印
        result.print();

    }

}
